package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @description：
 * @author: 曹旭
 * @date: 2022/5/22 03:39
 */
@RestController
@RequestMapping("shopping")
public class OrderCoreController {

    @Autowired
    OrderCoreService orderCoreService;

    @Autowired
    HttpServletRequest httpRequest;

    @PostMapping("order")
    public ResponseData createOrder(@RequestBody CreateOrderRequest request) {
        String userInfo = httpRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        if(object == null){
            throw new BizException(SysRetCodeConstants.GET_TOKEN_FAILED.getCode(), SysRetCodeConstants.GET_TOKEN_FAILED.getMessage());
        }
        Long uid = Long.parseLong(object.get("id").toString());
        request.setUserId(uid);
        CreateOrderResponse response = orderCoreService.createOrder(request);
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getOrderId(),"success");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @PostMapping("cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request) {
        CancelOrderResponse response = orderCoreService.cancelOrder(request);
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData("成功","success");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    @DeleteMapping("order/{id}")
    public ResponseData deleteOrder(@PathVariable String id) {
        DeleteOrderRequest deleteOrderRequest = new DeleteOrderRequest();
        deleteOrderRequest.setOrderId(id);
        DeleteOrderResponse response = orderCoreService.deleteOrder(deleteOrderRequest);
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData("成功","success");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
